<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/20
 * Time: 14:40
 */
namespace app\index\controller;

use app\index\model\Selltea as Sell;
use think\Db;
use think\Request;
use think\Config;

class Selltea extends Common
{
	protected $selltea = '';
	//判断是否登录
	public function _initialize()
	{
		parent::_initialize();
		$this->selltea = new Sell();
	}
	
	/**
	 * 查看结算首页
	 * @param string get.id 店id
	*/
	public function index()
	{
		$sid = input('get.sid');
		return view('index',compact('sid'));
	}
	
	/**
	 * 查询结算信息
	 * @param string get.sid 店id
	 * @param string get.rows 每页显示的条数
	 * @param string get.page 第几页
	 * @param string get.titles 要检索的字段
	*/
	public function info()
	{
		$sid = input('get.sid');
		$where = [];
		$rows = input('get.rows');
		$page = input('get.page');
		if(!empty(input('get.title'))){
			$title = input('get.title');
			//$where['time'] = ['like',"%{$title}%"];
			$where['ordernumber'] = ['like',"%{$title}%"];
		}
		//结算总条数
		$total = $this->selltea->whereOr($where)->group('ordernumber')->where('status',1)->where('sid',$sid)->count();
		//查询信息
		$rows = $this->selltea->whereOr($where)->where('sid',$sid)->where('status',1)
			->group('ordernumber')->order("id desc")->limit($rows)->page($page)->select();
		//时间转义
		foreach($rows as &$val){
			$val['time'] = date("Y-m-d H:i:s",$val['time']);
		}
		//分页时需要获取记录总数，键值为 total
		$result["total"] = $total;
		//获取的记录
		$result["rows"] = $rows;
		return json($result);
	}
	
	/**
	 * 订单详情
	 * @param string get.ordernumber 订单号

	*/
	public function detail()
	{
		$ordernumber = input('get.ordernumber');
		return view('detail',compact('ordernumber'));
	}
	
	/**
	 * 订单详情信息
	 * @param string get.ordernumber订单号
	 * @param string get.rows 每页显示的条数
	 * @param string get.page 第几页
	 * @param string get.titles 要检索的字段
	*/
	public function detailInfo()
	{
		$ordernumber = input('get.ordernumber');
		$where = [];
		$rows = input('get.rows');
		$page = input('get.page');
		if(!empty(input('get.title'))){
			$title = input('get.title');
			//$where['time'] = ['like',"%{$title}%"];
			$where['selltea.ordernumber'] = ['like',"%{$title}%"];
			$where['tea.name'] = ['like',"%{$title}%"];
		}
		//结算总条数
		$total = Db::table('selltea')
			->join('tea','tea.id = selltea.teaid','LEFT')
			->whereOr($where)->where('selltea.status',1)->where('selltea.ordernumber',$ordernumber)->count();
		//查询信息
		$rows = Db::table('selltea')->field('selltea.price,selltea.type,selltea.number,selltea.ordernumber,
				selltea.time,tea.name')
			->join('tea','tea.id = selltea.teaid','LEFT')
			->whereOr($where)->where('ordernumber',$ordernumber)
			->where('selltea.status',1)->order("selltea.id desc")->limit($rows)->page($page)->select();
		//时间转义
		foreach($rows as &$val){
			$val['time'] = date("Y-m-d H:i:s",$val['time']);
		}
		//分页时需要获取记录总数，键值为 total
		$result["total"] = $total;
		//获取的记录
		$result["rows"] = $rows;
		return json($result);
	}
	
	/**
	 * 结算
	 * @param string post.totalprice 总价
	 * @param string post.sid 店铺id
	 * 具体参数看方法
	*/
	public function settlement(Request $request)
	{
		if(request()->isAjax()){
			try{
				$input['total'] = $request->param('totalprice');
				$input['time'] = time();
				$input['ordernumber'] = time();
				$input['sid'] = $request->param('sid');
				$total = json_decode($request->param('total'));
				Db::startTrans();
				foreach($total as $val){
					//tea表id
					$input['teaid'] = $val[0];
					//单价
					$input['price'] = $val[2];
					//类别
					$input['type'] = $val[3];
					//购买个数
					$input['number'] = $val[4];
					//执行添加
					$result[] = $this->selltea->insertGetId($input);
					if(count($result) == 0){
						throw new \PDOException('结算失败');
					}
				}
				Db::commit();
				$value = Db::table('address')->where('sid',$input['sid'])->find();
				$info = Db::table('selltea')->field('tea.name,selltea.price,selltea.number,selltea.type')
					->join('tea','tea.id = selltea.teaid','LEFT')
					->whereIn('selltea.id',$result)->select();
				$orderInfo = $this->typesetting($info,14,7,3,$value['address']);
				$resultMsg = json_decode(order_print($orderInfo,1,$value['printid']));
				if($resultMsg -> ret != 0){
					throw new \PDOException($resultMsg->msg);
				}
				$success = ['success'=>'结算成功'];
				return json($success);
			}catch (\PDOException $e){
				Db::rollback();
				$error = ['error'=>$e->getMessage()];
				return json($error);
			}
		}
	}
	/**
	 * 飞鹅云排版
	 * @param $arr 要排版的数据
	 * @param $A 名称14
	 * @param $B 单价7
	 * @param $C 数量3
	 * @param $address 打印地址
	 */
	function typesetting($arr,$A,$B,$C,$address)
	{
		$nums = 0;
		$orderInfo = '<CB>新品有戏</CB><BR>';
		$orderInfo .= '名称           单价   数量<BR>';//名称14 单价7 数量3 金额6-->这里的字节数可按自己需求自由改写
		$orderInfo .= '--------------------------------<BR>';
		foreach ($arr as $k5 => $v5) {
			if($v5['type'] == 1){
				$name = $v5['name']."(大杯)";
			}else if($v5['type'] == 2){
				$name = $v5['name']."(中杯)";
			}else if($v5['type'] == 3){
				$name = $v5['name']."(小杯)";
			}
			$price = $v5['price'];
			$num = $v5['number'];
			//$prices = $v5['classid'];
			$kw3 = '';
			$kw1 = '';
			$kw2 = '';
			$kw4 = '';
			$str = $name;
			$blankNum = $A;//名称控制为14个字节
			$lan = mb_strlen($str,'utf-8');
			$m = 0;
			$j=1;
			$blankNum++;
			$result = array();
			for ($i=0;$i<$lan;$i++){
				$new = mb_substr($str,$m,$j,'utf-8');
				$j++;
				if(mb_strwidth($new,'utf-8')<$blankNum) {
					if($m+$j>$lan) {
						$m = $m+$j;
						$tail = $new;
						$lenght = iconv("UTF-8", "GBK//IGNORE", $new);
						$k = $A - strlen($lenght);
						for($q=0;$q<$k;$q++){
							$kw3 .= ' ';
						}
						$tail .= $kw3;
						break;
					}else{
						$next_new = mb_substr($str,$m,$j,'utf-8');
						if(mb_strwidth($next_new,'utf-8')<$blankNum) continue;
						else{
							$m = $i+1;
							$result[] = $new.'<BR>';
							$j=1;
						}
					}
				}
			}
			$head = '';
			foreach ($result as $value) {
				$head .= $value;
			}
			if(strlen($price) < $B){
				$k1 = $B - strlen($price);
				for($q=0;$q<$k1;$q++){
					$kw1 .= ' ';
				}
				$price = $price.$kw1;
			}
			if(strlen($num) < $C){
				$k2 = $C - strlen($num);
				for($q=0;$q<$k2;$q++){
					$kw2 .= ' ';
				}
				$num = $num.$kw2;
			}
//			if(strlen($prices) < $D){
//				$k3 = $D - strlen($prices);
//				for($q=0;$q<$k3;$q++){
//					$kw4 .= ' ';
//				}
//				$prices = $prices.$kw4;
//			}
			$orderInfo .= $head.$tail.' '.$price.' '.$num.'<BR>';
			@$nums += $price * $num;
		}
		$time = date('Y-m-d H:i:s',time());
		$orderInfo .= '--------------------------------<BR>';
		$orderInfo .= '合计：'.$nums.'元<BR>';
		$orderInfo .= '卖出地址：'.$address.'<BR>';
		$orderInfo .= '购买时间：'.$time.'<BR>';
		$orderInfo .= '<QR>https://mp.weixin.qq.com/a/~TvISZDOmlZ9gC_3qVT7_fQ~~</QR>';
		return $orderInfo;
	}

}